<?php

namespace App\Http\Controllers\Rent\Product;

use App\Http\Controllers\ShopController;
use App\Models\Business\Record as RecordModel;
use App\Models\Config as ConfigModel;
use App\Models\Product\Lease as LeaseModel;
use App\Models\Product\Product as ProductModel;
use App\Models\Region as RegionModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class LeaseController extends ShopController
{
    public function add()
    {
        $params = request()->input();

        $business = request()->get('business');

        if($business['auth'] == 0)
        {
            return $this->error('请先认证');
        }

        $product = ProductModel::where('rentstatus','<>','1')->where('status','1')->where('id',$params['proid'])->first();

        if(!$product)
        {
            return $this->error('商品不存在');
        }

        // 判断商品库存是否充足
        $UpdateStock = bcsub($product['stock'],1);
        
        if($UpdateStock < 0)
        {
            return $this->error('商品库存不足');
        }

        $UpdateMoney = bcsub($business['money'],$params['rent']);

        if($UpdateMoney < 0)
        {
            return $this->error('余额不足，请及时充值');
        }

        $data = [
            'busid' => $business['id'],
            'proid' => $product['id'],
            'rent' => bcsub($params['rent'],$params['price'],2),
            'price' => $params['price'],// 租用的时间费用
            'nickname' => trim($params['nickname']),
            'mobile' => trim($params['mobile']),
            'address' => trim($params['address']),
            'createtime' => $params['start'],
            'endtime' => $params['end'],
            'status' => 1
        ];

        $RegionPath = RegionModel::where('code',$params['code'])->value('parentpath');

        if(!$RegionPath)
        {
            return $this->error('所选地区不存在');
        }

        [$province,$city,$district] = explode(',',$RegionPath);

        $data['province'] = $province ?? null;
        $data['city'] = $city ?? null;
        $data['district'] = $district ?? null;

        // 封装图片数据
        $card = new \CURLFile($_FILES['card']['tmp_name'],$_FILES['card']['type'],$_FILES['card']['name']);

        // 查询fastpro线上地址
        $url = ConfigModel::where('name','url')->value('value');

        // 判断是否开发环境
        $url = env('SITE_URL',$url);

        // 拼接地址并且上传 为了统一上传接口，暂时不重写接口，直接用用户上传图片接口
        $resJson = httpRequest($url . '/base/business/upload',['avatar' => $card,'id' => $business['id']]);

        $res = json_decode($resJson,true);

        if($res['code'] === 0)
        {
            return $this->error($res['msg']);
        }

        $data['card'] = $res['data'];

        // 定义验证器
        $validate = [
            [
                'busid' => 'required', //必填
                'proid' => 'required', //必填
                'rent' => 'required|numeric|gte:0', //必填
                'price' => 'required|numeric|gte:0', //必填
                'createtime' => 'required',
                'endtime' => 'required', //结束时间
                'address' => 'required', //详细地址
                'card' => 'required', //详细地址
                'expcode' => 'unique:lease',
                'busexpcode' => 'unique:lease',
                'status' => 'numeric|in:1,2,3,4,5,6',  //给字段设置范围
            ],
            [
                'busid.required'  => '用户信息未知',
                'proid.required'  => '租用商品信息未知',
                'rent.required'  => '押金必填',
                'rent.numeric'  => '押金必须是数字',
                'rent.gte'  => '押金必须大于0元',
                'price.required'  => '租金必填',
                'price.numeric'  => '租金必须是数字',
                'price.gte'  => '租金必须大于0元',
                'createtime.required'  => '开始时间未知',
                'endtime.required'  => '结束时间未知',
                'address.required'  => '请输入详细地址',
                'card.required'  => '请上传身份证照片',
                'expcode.unique' => '物流单号已存在，请重新输入',
                'busexpcode.unique' => '物流单号已存在，请重新输入',
                'status.in' => '租赁状态有误',
            ]
        ];

        // 创建验证器
        $validator = Validator::make($data,...$validate);

        if($validator->fails())
        {
           return $this->error($validator->errors()->first());
        }

        DB::beginTransaction();

        /* 
            创建一个租赁订单
            更新用户余额
            更新库存
            新增一条消费记录
        */

        // 创建一个租赁订单
        $LeaseStatus = LeaseModel::create($data);

        // 更新用户余额
        $business->money = $UpdateMoney;

        $BusinessStatus = $business->save();

        // 更新库存
        $product->stock = $UpdateStock;

        $ProductStatus = $product->save();

        // 创建一条消费记录
        $RecordData = [
            'busid' => $business['id'],
            'total' => $params['rent'],
            'content' => "您租赁了【{$product['name']}】了，消费了￥ {$params['rent']} 元"
        ];

        // 定义验证器
        $validate = [
            [
                'busid' => 'required', //必填
                'total' => 'required', //必填
                'content' => 'required', //必填
            ],
            [
                'busid.required'  => '用户信息未知',
                'total.required'  => '消费金额未知',
                'content.required'  => '消费详情未知'
            ]
        ];

        // 创建验证器
        $validator = Validator::make($RecordData,...$validate);

        if($validator->fails())
        {
           return $this->error($validator->errors()->first());
        }

        $RecordStatus = RecordModel::create($RecordData);

        if($LeaseStatus === false || $BusinessStatus === false || $ProductStatus === false || $RecordStatus === false)
        {
            httpRequest($url . '/base/business/del',['avatar' => $data['card'],'id' => $business['id']]);
            DB::rollBack();
            return $this->error('租赁失败');
        }else{
            DB::commit();
            return $this->success('租赁成功');
        }
    }
}
